package server;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class TopicBasedLogger extends Thread {
	
	private static final int NEXT_LOG = 5000;
	
	private TopicBasedServer server;
	BufferedWriter out;
	private boolean stop = false;
	private long start = 0;

	public TopicBasedLogger(TopicBasedServer server) {
		this.server = server;
		try {
			this.out = new BufferedWriter(new FileWriter(new File("src/log/tb_" + server.getId() + ".txt")));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		int time = 0;

		System.out.println("Logger started ... \n");
		
		while(new Date().getTime() % NEXT_LOG != 0) {
			// dummy loop to synchronize logging
		}
		
		this.start = new Date().getTime();
		
		while(!stop) {
			time = (int) (new Date().getTime()-start)/(NEXT_LOG);
			try {
				out.write(time + " " + server.getRunningJobs() + "\n");
				out.flush();
				Thread.sleep(NEXT_LOG);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close() {
		stop = true;
	}

}
